﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZX.BLL;
using ZX.EHR.Library;
using ZX.Common;
using System.Web.Security;
using ZX.BLL.Extend;
using ZX.DBModule;
namespace ZX.WebApp.Mobi.proc
{
    /// <summary>
    /// login 的摘要说明
    /// </summary>
    public class login : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(CheckLogin(context.Request["uname"], context.Request["upass"]));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string CheckLogin(string uname,string pwd)
        {
            BUser buser = new BUser();
            DatUser dtusr = new DatUser();
            dtusr.LoginName = uname.Trim();
            dtusr.Password = ExtendMethods.GetMd5Hash(pwd.Trim());
            DatUser user = buser.GetDatUserByLoginNameAndPwd(dtusr);

            if (user == null)
            {
                return "N";
            }
            else
            {
                //用户登录时判断是否过期
                if (buser.IsExpire(dtusr))
                {
                    return "P"; 
                }
                else
                {
                    WriteLog(user);
                    FormsAuthentication.SetAuthCookie(user.LoginName, true);

                    HttpContext.Current.Session["User"] = user;
                    HttpContext.Current.Session["IsOutSite"] = user.IsOutsite;
                    //return "flightHandler({\"back\":\"1\"});";
                    return "1";
                }
            }
        }

        /// <summary>
        /// 写登录日志
        /// </summary>
        private void WriteLog(DatUser user)
        {
            BaseBussnies buss = new BaseBussnies();
            SysDataLog log = new SysDataLog();
            log.UserID = user.UserID;
            log.Action = "Mobi_Login";
            log.Data = "IP:" +HttpContext.Current.Request.UserHostAddress+ ",LoginName:" + user.LoginName;
            log.EntityName = "DatUser";
            log.LogTime = DateTime.Now;
            buss.entity = log;
            buss.Insert();
        }
    }
}